package com.example.util;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidator;

import java.util.Set;


public class ValidationUtil {

    // Validator是线程安全的，而且可以重复使用
    private static volatile Validator failFastValidator;

    private static volatile Validator notFailFastValidator;

    public static Validator getFailFastValidator(){
        if(failFastValidator == null){
            synchronized (ValidationUtil.class){
                if(failFastValidator == null){
                    ValidatorFactory factory = Validation.byProvider(HibernateValidator.class)
                            .configure()
                            .failFast(true) // 开启快速失败
                            .buildValidatorFactory();
                    failFastValidator = factory.getValidator();
                }
            }
        }
        return failFastValidator;
    }

    public static Validator getNotFailFastValidator(){
        if(notFailFastValidator == null){
            synchronized (ValidationUtil.class){
                if(notFailFastValidator == null){
                    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
                    notFailFastValidator = factory.getValidator();
                }
            }
        }
        return notFailFastValidator;
    }

    public static <T> Set<ConstraintViolation<T>> validateWithFailFast(T object){
        Set<ConstraintViolation<T>> constraintViolations  = getFailFastValidator().validate(object);
        return constraintViolations;
    }

    public static <T> Set<ConstraintViolation<T>> validateWithoutFailFast(T object){
        Set<ConstraintViolation<T>> constraintViolations  = getNotFailFastValidator().validate(object);
        return constraintViolations;
    }
}
